package cn.erperp.cdc.maxwell.service;


import cn.erperp.cdc.maxwell.dao.BusEventsApiEntityDao;
import cn.erperp.cdc.maxwell.dao.BusEventsApiHistoryEntityDao;
import cn.erperp.cdc.maxwell.dao.BusEventsApiWaitAckEntityDao;
import cn.erperp.cdc.maxwell.entity.BusEventsApiHistoryEntity;
import cn.erperp.cdc.maxwell.entity.BusEventsApiWaitAckEntity;
import cn.erperp.cdc.maxwell.msg.AckMessageVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

@Service
@Slf4j
public class MessageService {



    @Autowired
    BusEventsApiEntityDao busEventsApiEntityDao;

    @Autowired
    BusEventsApiWaitAckEntityDao busEventsApiWaitAckEntityDao;
    @Autowired
    BusEventsApiHistoryEntityDao busEventsApiHistoryEntityDao;

    /**
     * 消息处理完了,主动ack消息
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean ackMessage(AckMessageVO ackMessageVO){
        Optional<BusEventsApiWaitAckEntity> busEventsApiWaitAckEntity = busEventsApiWaitAckEntityDao.findById(ackMessageVO.getMessageId());
        if (!busEventsApiWaitAckEntity.isPresent()){
            log.error("不存在的消息 {}",ackMessageVO.getMessageId());
            return false;
        }
        //删除待确认消息
        BusEventsApiWaitAckEntity eventsApiWaitAckEntity = busEventsApiWaitAckEntity.get();
        busEventsApiWaitAckEntityDao.deleteById(eventsApiWaitAckEntity.getId());

        //移动到历史消息
        BusEventsApiHistoryEntity busEventsApiHistoryEntity = new BusEventsApiHistoryEntity();
        BeanUtils.copyProperties(eventsApiWaitAckEntity,busEventsApiHistoryEntity);
        busEventsApiHistoryEntityDao.save(busEventsApiHistoryEntity);

        return true;
    }
}
